package com.xiaotu.common.util;

import java.util.concurrent.*;

/**
 * @类名 ThreadPool
 * @日期 2015年7月3日
 * @作者 高海军
 * @功能 线程池
 */
public class ThreadPool
{
    private static final int POOL_CORE = 200;//核心线程数

    private static final int POOL_SIZE = 500;//最大线程数

    private static final int WORK_QUEUE_RATE = 5;//任务等待队列大小占总线程数的比例

    private static final long ALIVE_TIME = 30L;//闲置线程存活时间（单位：分钟）

    private static ExecutorService pool;

    static
    {
        pool = new ThreadPoolExecutor(POOL_CORE, POOL_SIZE, ALIVE_TIME, TimeUnit.MINUTES, new LinkedBlockingQueue<>
                (POOL_SIZE / WORK_QUEUE_RATE), new ThreadPoolExecutor.AbortPolicy());
    }

    public static void execute(Runnable runnable)
    {
        pool.execute(runnable);
    }

    public static <V> V futureGet(Callable<V> callable, int timeOut)
            throws InterruptedException, ExecutionException, TimeoutException
    {
        Future<V> future = pool.submit(callable);
        return future.get(timeOut, TimeUnit.MILLISECONDS);
    }

    public static void shutdown()
    {
        if (pool != null)
            pool.shutdown();
    }

}
